<?php

/**
 * 获取请求参数
 * @param array $param
 * @return mixed
 * @author 我只想看看蓝天 <1207032539@qq.com>
 */
function getRequestParam(array $param = [])
{
    $res = request()->input();
//    array_walk_recursive($res, function (&$value) {
//        $value = is_null($value) ? '' : $value;
//    });
    if (!empty($param)) {
        $res = array_filter($res, function ($key) use ($param) {
            if (in_array($key, $param)) {
                return true;
            }
            return false;
        }, ARRAY_FILTER_USE_KEY);
    }
    return $res;
}

/**
 * 自定义请求参数验证方法
 * @param $rules
 * @param array $messages
 * @param array $customAttributes
 * @author 我只想看看蓝天 <1207032539@qq.com>
 */
function checkData(array $param, array $rules, array $messages = [], array $customAttributes = [])
{
    if (is_array($rules)) {
        //解析字段，提取字段别名
        foreach ($rules as $key => $value) {
            if (count($field = explode('|', $key)) == 2) {
                $customAttributes[$field[0]] = $field[1];
                $rules[$field[0]] = $value;
                unset($rules[$key]);
            }
        }
    }
    $error = validator($param, $rules, $messages, $customAttributes);
    if ($error->fails()) {
        throw new \App\Exceptions\CommonException($error->errors()->first());
    }
}

/**
 * 打印下面最近一条执行的sql语句
 * @author 我只想看看蓝天 <1207032539@qq.com>
 */
function sql_dump(bool $block_after_first = true, bool $begin_transaction = true)
{
    $begin_transaction && \Illuminate\Support\Facades\DB::beginTransaction(); //开启事务防止操作性语句执行，但自增id增长无可避免
    \Illuminate\Support\Facades\DB::listen(function ($query) use ($block_after_first) {
        $bindings = $query->bindings;
        $sql = $query->sql;
        foreach ($bindings as $replace) {
            $value = is_string($replace) ? "'" . $replace . "'" : $replace;
            $sql = preg_replace('/\?/', $value, $sql, 1);
        }
        $sql .= ' 耗时:' . $query->time . 'ms';
        $block_after_first ? dd($sql) : dump($sql);
    });
}
